//
//  JDOAuthTableViewController.swift
//  JDWeiBo
//
//  Created by apple on 15/6/26.
//  Copyright © 2015年 apple. All rights reserved.
//

import UIKit
import SVProgressHUD

class JDOAuthTableViewController: UIViewController, UIWebViewDelegate {

   private let WB_client_id = "4228358972"
   private let WB_redirect_uri = "http://www.baidu.com"
    private let WB_App_Secret = "9cd1325889d0741e60ac6173d14e5d47"
    
    // 加载webView页面
    lazy var webView : UIWebView? = {
        // 实例化
        let wv = UIWebView()
        
        // web 设置代理
        wv.delegate = self
        
        return wv
    }()
    
    override func loadView() {
        
        // 跟视图就是webView
        view = webView
        
        // 设置导航栏信息
        title = "新浪微博"
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
    }
    // 导航按妞关闭方法
    func close() {
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        loadOAuth()
        
    }
    private func loadOAuth() {
        // 加载授权的页面
        
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(WB_client_id)&redirect_uri=\(WB_redirect_uri)"
        
        let url = NSURL(string: urlString)!
        
        webView?.loadRequest(NSURLRequest(URL: url))
    }
    
    // 如果是新浪微博 URL 就继续加载 如果是回调 就判断是否授权码
    /**
    登入成功、
    https://api.weibo.com/oauth2/authorize?client_id=4228358972&redirect_uri=http://www.baidu.com 
    https://api.weibo.com/oauth2/authorize
    
    http://www.baidu.com/?code=27ee5f7ee046405f39c090a8422d2fa3
    
    取消授权
    http://www.baidu.com/?error_uri=%2Foauth2%2Fauthorize&error=access_denied&error_description=user%20denied%20your%20request.&error_code=21330
    */
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
//        print("-----\(request)")
        
        let urlString = request.URL!.absoluteString
        
        // 判断是回调地址就根据URL中的内容判断是否授权码
        if !urlString.hasPrefix(WB_redirect_uri) {
            return true
        }
        print("需要判断")
        let query = request.URL!.query!
        
        let codeStr = "code="
        
        if query.hasPrefix(codeStr) {
            print("获取授权")
            
            // 拿到授权码
            let code = (query as NSString).substringFromIndex((codeStr as NSString).length)
            
            print("code=\(code)")
            
            loadAccessToken(code)
            
        } else {
            print("取消授权")
            close()
        }
        
        return false
        
        }
    // 结束加载 Finish
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    // 开始加载 Start
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    // 使用授权码加载 token
    private func loadAccessToken(code: String) {
        // 换取令牌URL借口 HTTP的请求方式
        let urlString = "oauth2/access_token"
        
        // 设置请求参数
        let params = ["client_id" : WB_client_id,
                      "client_secret" : WB_App_Secret,
                      "grant_type" : "authorization_code",
                      "code" : code,
                      "redirect_uri" : WB_redirect_uri]
        
        // 发起网络请求
        JDNetworkTools.sharedNetworkTools().POST(urlString, parameters: params, success: { (_, JSON) -> Void in
            
//            print(JSON)
            // 字典转模型
            JDUserAccount(dict: JSON as! [String : AnyObject]).loadUserInfo {(account,error) -> () in
                
                if account != nil {
                    
                    print(account)
                    // 1. 设置全局的 account
                    sharedUserAccount = account
                    
                    // 2. 发送通知
                    // object = false 表示显示 WelcomeViewController
                    NSNotificationCenter.defaultCenter().postNotificationName(JDSwitchRootVCNotification, object: false)
                    
                    // 强烈不建议写！
                    // UIApplication.sharedApplication().keyWindow?.rootViewController = WelcomeViewController()
                    
                    // 3. 关闭当前控制器
                    self.close()
                    return
                }
            print(error)
            SVProgressHUD.showInfoWithStatus("网络不给力")
        }
        
            }) { (_, error) -> Void in
                print(error)
                SVProgressHUD.showInfoWithStatus("网络不给力")
        }
    }
}






























